package de.uhlesoluschns.opensearch.ui;

import com.admob.android.ads.AdView;

import de.uhlesoluschns.opensearch.R;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class Browser extends Activity {
	
	private WebView webView;
	private AdView adView;
	
	private class JsExternal {
		public void AddSearchProvider(String url) {
			startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url), Browser.this, SearchProvider.class));
		}
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_PROGRESS);
		setContentView(R.layout.browser);
		
		adView = (AdView) findViewById(R.id.adView);
		adView.setRequestInterval(60);	//TODO do in xml
		
		webView = (WebView) findViewById(R.id.webView);
		WebSettings webSettings = webView.getSettings();
		webSettings.setJavaScriptEnabled(true);
		webSettings.setBuiltInZoomControls(true);
		
		webView.addJavascriptInterface(new JsExternal(), "external");
		
		webView.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				Browser.this.setProgress(newProgress * 100);
			}
		});
		
		webView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return true;
			}
			
			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				Toast.makeText(Browser.this, description, Toast.LENGTH_SHORT).show();
			}
			
		});
		webView.loadUrl(getIntent().getDataString());
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
			webView.goBack();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
}
